import Taro from '@tarojs/taro'
import React, { useCallback, useState } from 'react'
import { View, Input, Text } from '@tarojs/components'
import { validation } from '@pier88health/p8h-common'
import i18n from '@I18N'
import Countdown from '@COMPONENTS/Countdown'
import './AuthCodeInput.scss'

const AuthCodeInput = ({
  code, phone, placeholder, onInput, getAuthCode
}) => {
  const isValidPhoneNumber = validation.isPhoneNumber(phone)
  const [canClick, setCanClick] = useState(true)
  const [isAlreadyGet, setAlreadyGet] = useState(false)
  const onClick = useCallback(() => {
    if (isValidPhoneNumber) {
      setCanClick(false)
      !isAlreadyGet && setAlreadyGet(true)
      getAuthCode()
      Taro.showToast({
        icon: 'none',
        title: `${i18n.login.has_send_code()} ${phone}`,
      })
    } else if (phone.length === 11) {
      Taro.showToast({
        icon: 'none',
        title: i18n.login.phone_format_error(),
      })
    }
  }, [phone, setCanClick, isAlreadyGet, setAlreadyGet, isValidPhoneNumber, getAuthCode])
  const onFinish = useCallback(() => setCanClick(true), [setCanClick])
  return (
    <View className="input-container">
      <Input
        type="number"
        value={code}
        className="code-input"
        placeholder={placeholder}
        placeholderClass="placeholderCode"
        onInput={onInput}
        maxlength={4}
      />
      <View className="countdown">
        {
          canClick ? (
            <View className={`btn-get-code ${isValidPhoneNumber ? '' : 'btn-invalid'}`} onClick={onClick}>
              <Text className={`text-get-code ${isAlreadyGet ? 'once-more' : ''} ${isValidPhoneNumber ? '' : 'invalid'}`}>
                {i18n.login[isAlreadyGet ? 'reacquire' : 'get_auth_code']()}
              </Text>
            </View>
          ) : <Countdown until={60} onFinish={onFinish} />
        }
      </View>
    </View>
  )
}

export default AuthCodeInput
